package net.xiduth.game.player.content.citadels.other;

import net.xiduth.cores.CoresManager;
import net.xiduth.game.RegionBuilder;
import net.xiduth.game.player.Player;
import net.xiduth.game.player.content.FadingScreen;
import net.xiduth.game.tasks.WorldTask;
import net.xiduth.game.tasks.WorldTasksManager;
import net.xiduth.utils.Logger;

/**
 * @author Jae
 * Represents the battlefield.
 */
public class BattleField {
	
	/**
	 * 
	 * @param Rx
	 *         from region x
	 * @param Ry
	 *         to region y
	 * @param clan
	 *         clan or pvp
	 * @param player
	 *         player being added
	 */

	public BattleField(final int Rx, final int Ry, boolean clan, final Player player) {
		player.lock();
		final long time = FadingScreen.fade(player);
		CoresManager.slowExecutor.execute(new Runnable() {
			@Override
			public void run() {
				try {
					player.closeInterfaces();
					player.lock();
					CoresManager.slowExecutor.execute(new Runnable() {
						@Override
						public void run() {
							try {
								boolean needDestroy = mapBase != null;
								final int[] oldMapBaseCoords = mapBase;
								mapBase = RegionBuilder.findEmptyChunkBound(40, 40);
								RegionBuilder.copyAllPlanesMap(Rx, Ry, mapBase[0],
										mapBase[1], 40);
								if (needDestroy) {
									WorldTasksManager.schedule(new WorldTask() {
										@Override
										public void run() {
											CoresManager.slowExecutor
													.execute(new Runnable() {
														@Override
														public void run() {
															try {
																RegionBuilder
																		.destroyMap(
																				oldMapBaseCoords[0],
																				oldMapBaseCoords[1],
																				8, 8);
															} catch (Exception e) {
																e.printStackTrace();
															} catch (Error e) {
																e.printStackTrace();
															}
														}
													});
										}
									});
								}
							} catch (Exception e) {
								e.printStackTrace();
							} catch (Error e) {
								e.printStackTrace();
							}

						}
					});
					FadingScreen.unfade(player, time, new Runnable() {
						@Override
						public void run() {
							//AddPlayerToCitadel(player);
							player.unlock();
						}	
					});
					
				} catch (Throwable e) {
					Logger.handle(e);
				}
			}
		});
			
		}
	
		
	
	public static transient int[] mapBase;
}
